import { Injectable } from "@angular/core";
import { HttpErrorResponse } from "@angular/common/http";

import { Actions, Effect, ofType } from "@ngrx/effects";
import { Router } from "@angular/router";
import { switchMap, map, catchError } from "rxjs/operators";
import { of } from "rxjs/observable/of";

import { 
    UserActionTypes, 
    UserLogin, 
    UserLoginFail, 
    UserLoginSuccess, 
    LoadUserInfo, 
    LoadUserInfoSuccess, 
    LoadUserInfoFail, 
    UserLogout, 
    UserLogoutSuccess, 
    UserLogoutFail 
} from "../actions";
import { UserService, LocalstoreService } from "../../shared/services";
import { UserToken, UserInfo } from "../../shared/modes";


@Injectable()
export class UserEffects {

    constructor(
        private router: Router,
        private actions$: Actions,
        private userService: UserService,
        private localstorage: LocalstoreService
    ) {}

    @Effect()
    UserLogin$ = this.actions$
        .pipe(
            ofType(UserActionTypes.USER_LOGIN),
            switchMap((action: UserLogin) => {
                return this.userService.login(action.payload).pipe(
                    map((userToken: UserToken) => new UserLoginSuccess(userToken)),
                    catchError((error: HttpErrorResponse) => of(new UserLoginFail(error)))
                );
            })
        );
    
    @Effect()
    LoadUserInfo$ = this.actions$
        .pipe(
            ofType(UserActionTypes.LOAD_USER_INFO),
            switchMap((action: LoadUserInfo) => {
                return this.userService.userInfo(action.payload).pipe(
                    map((userInfo: UserInfo) => new LoadUserInfoSuccess(userInfo)),
                    catchError((error: HttpErrorResponse) => of(new LoadUserInfoFail(error)))
                );
            })
        );

    @Effect()
    LogoutUser$ = this.actions$
        .pipe(
            ofType(UserActionTypes.USER_LOGOUT),
            switchMap((action: UserLogout) => {
                return this.userService.logout(action.payload).pipe(
                    map(() => new UserLogoutSuccess()),
                    catchError((error: HttpErrorResponse) => of(new UserLogoutFail(error)))
                );
            })
        );

}